package com.lagou.edu.support;

import com.alibaba.druid.pool.DruidDataSource;
import com.lagou.edu.annotations.Component;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author edward
 * @ProjectName ConnectionUtil
 * @Description TODO 数据库连接池
 * @time 2022/4/4 4:58 下午
 */
// @Component(value="connectionUtil")
@Component
public class ConnectionUtil {
    private static DruidDataSource dataSource = new DruidDataSource();

    static {
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/mydatabase");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
    }

    public ThreadLocal<Connection> currentConnection = new ThreadLocal<>();// 存储当前线程的连接

    /**
     * 从当前线程获取连接
     */
    public Connection getCurrentConnection() throws SQLException {
        if (null == currentConnection.get()) {
            // 从连接池拿连接并绑定到线程
            Connection connection = dataSource.getConnection();
            // 绑定到当前线程
            currentConnection.set(connection);
            return connection;
        }
        return currentConnection.get();
    }
}
